package com.yanqu.road.server.gameplayer.module.cricket;

import com.yanqu.road.dao.impl.player.cricket.CricketDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.cricket.*;
import com.yanqu.road.entity.cricket.config.*;
import com.yanqu.road.entity.cricket.helper.CricketFightForcePro;
import com.yanqu.road.entity.cricket.helper.PreWarInspireSkillInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eSkillType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.player.PatronsCricketBindingData;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.logic.bussiness.config.CricketConfigBusiness;
import com.yanqu.road.logic.bussiness.player.UserCricketBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.model.cricket.CricketUserBaseInfo;
import com.yanqu.road.pb.cricket.CricketProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.cmd.cricket.CricketWatchUserServiceCmd;
import com.yanqu.road.server.game.service.GameService;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.cricket.battle.CricketBattle;
import com.yanqu.road.server.gameplayer.module.cricket.entity.DbUserCricketBattleLog;
import com.yanqu.road.server.gameplayer.module.cricket.entity.DbUserCricketBattleLogDetail;
import com.yanqu.road.server.gameplayer.module.cricket.model.CricketBattleData;
import com.yanqu.road.server.gameplayer.module.cricket.model.CricketWaitHandleBattleLog;
import com.yanqu.road.server.gameplayer.module.cricket.entity.DbUserCricketWaitSendBattleLog;
import com.yanqu.road.server.gameplayer.module.cricket.entity.business.CricketGameBusiness;

import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.pb.CricketPb;
import com.yanqu.road.server.protocol.*;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CricketMgr extends TempMgr {

    private static RandomHelper randomHelper = new RandomHelper();
    private static Logger logger = LogManager.getLogger(CricketMgr.class.getName());
    private static CricketSystemConfig config;


    private static ConcurrentHashMap<Long, DbUserCricketWaitSendBattleLog> waitSendSyncCricketDbBattleLog = new ConcurrentHashMap<>();

    public static void initService(GameService syncMessageService) {
        // 查看他人蛐蛐
        syncMessageService.addGameServiceCommand(Protocol.S_CRICKET_SERVICE_WATCH_OTHER_USER, new CricketWatchUserServiceCmd());
    }

    public static CricketSystemConfig getConfig() {
        return config;
    }

    /**
     * 查看他人蛐蛐
     *
     * @param userId 用户id
     */
    public static CricketProto.CricketWatchPlayerSimpleRespMsg.Builder watch(long userId) {
        CricketProto.CricketWatchPlayerSimpleRespMsg.Builder builder = CricketProto.CricketWatchPlayerSimpleRespMsg.newBuilder();
        UserInfo userInfo = UserMgr.getUserInfo(userId);
        if(userInfo == null){
            builder.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
            return builder;
        }

        if(!SystemOpenMgr.offlineSystemOpen(userInfo.getSystemOpenValue(), eSystemId.Cricket.getValue())){
            builder.setRet(GameErrorCode.E_SYSTEM_NO_OPEN);
            return builder;
        }

        Map<Integer, CricketData> cricketDataMap = new HashMap<>();
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        cricketDataMap = player != null ?
                player.getModule(CricketModule.class).getCricketDataMap()
                : new CricketDaoImpl().getCricketDataMap(userId);
        for (CricketData cricketData : cricketDataMap.values()) {
            if (cricketData == null) {
                continue;
            }
            builder.addCricket(CricketPb.parseCricketTemp(cricketData));
        }
        builder.setRet(0);
        return builder;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        try {
            config = new CricketSystemConfig();
            config.setCricketConfigMap(CricketConfigBusiness.getCricketConfig());
            config.setCricketUpConfigMap(CricketConfigBusiness.getCricketUpConfig());
            config.setCricketScenceConfigMap(CricketConfigBusiness.getCricketScenceConfig());
            config.setCricketCourtConfigMap(CricketConfigBusiness.getCricketCourtConfig(ServerListMgr.getChannelId(GameServer.getInstance().getServerId())));
            // 获取最大的切换顺序
            config.initMaxOrder();

            initCricketFightForcePro();
            initCricketFightScore();

            return true;
        } catch (Exception e) {
            //e.printStackTrace();
            logger.error("cricket init config error", e.getCause());
        }
        return false;
    }

    private void initCricketFightForcePro() {
        String[] split = GameConfig.CRICKET_FIGHT_SCORE_PARAM.split("#");
        String[] split1 = split[0].split("\\|");
        for (String s : split1) {
            config.getCricketFightScoreAttack().add(Integer.parseInt(s));
        }

        String[] split2 = split[1].split("\\|");
        for (String s : split2) {
            config.getCricketFightScoreDefend().add(Integer.parseInt(s));
        }
    }

    private void initCricketFightScore() {
        String[] split = GameConfig.CRICKET_FIGHT_FORCE_PRO.split("\\|");
        CricketFightForcePro cricketFightForcePro = new CricketFightForcePro();
        cricketFightForcePro.setK1(Integer.parseInt(split[0]));
        cricketFightForcePro.setK2(Integer.parseInt(split[1]));
        cricketFightForcePro.setK3(Integer.parseInt(split[2]));
        cricketFightForcePro.setK4(Integer.parseInt(split[3]));
        cricketFightForcePro.setN1(Integer.parseInt(split[4]));
        cricketFightForcePro.setN2(Integer.parseInt(split[5]));
        cricketFightForcePro.setN3(Integer.parseInt(split[6]));
        config.setCricketFightForcePro(cricketFightForcePro);
    }

    @Override
    public boolean reloadData() throws Exception {
//        waitSendSyncCricketDbBattleLog = CricketGameBusiness.getDbUserCricketWaitSendBattleLogList();
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean save() {
//        for (DbUserCricketWaitSendBattleLog dbUserCricketWaitSendBattleLog : waitSendSyncCricketDbBattleLog.values()) {
//            CricketGameBusiness.saveDbUserCricketWaitSendBattleLog(dbUserCricketWaitSendBattleLog);
//        }
        return true;
    }

    public static Map<Long, Map<Integer, CricketData>> getSomeUserFishMap(List<Long> outLineUserList) {
        return UserCricketBussiness.getSomeFishDataMap(outLineUserList);

    }

    public static Map<Integer, CricketData> getUserCricketMap(long userId) {
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        if(null != player){
            Map<Integer, CricketData> cMap = player.getModule(CricketModule.class).getCricketDataMap();
            return cMap;
        }else {
            return UserCricketBussiness.getCricketDataMap(userId);
        }
    }
    public static CricketData getUserCricketByPatrons(int patronsId,Map<Integer, CricketData> cricketList){
        for (CricketData data : cricketList.values()) {
            if (data.getEquipPatronsId() == patronsId) {
                return data;
            }
        }
        return null;
    }

    public static long getCricketAddQualification(int patronsId, Map<Integer, CricketData> dataMap) {
        int qualification = 0;
        CricketData equipData = getUserCricketByPatrons(patronsId, dataMap);
        if (equipData != null) {
            for (CricketEquipSkill skillData : equipData.getEquipSkillList()) {
                SkillInfo skillInfo = SkillMgr.getSkillInfo(skillData.getSkillId());
                if (skillInfo != null && skillInfo.getType() == eSkillType.Qualification.getValue()) {
                    //现在没等级，默认1级
                    qualification += SkillMgr.getSkillAddition(skillInfo, skillData.getLv());
                }
            }
        }
        return qualification;
    }

    public static int getCricketEquipCost(int buyTimes) {
        int ingots = GameConfig.CRICKET_EQUIP_BASE_COST + GameConfig.CRICKET_EQUIP_ADD_COST * buyTimes;
        if(ingots < 0){
            ingots = 0;
        }
        if(ingots > GameConfig.CRICKET_EQUIP_MAX_COST){
            ingots = GameConfig.CRICKET_EQUIP_MAX_COST;
        }
        return ingots;
    }

    public static void offLine(GamePlayer player) {

    }

    public static void processBattleResult(CricketBattle cricketBattle) {
        long t1 = System.currentTimeMillis();
        CricketProto.CricketBattleLog.Builder battleLog = cricketBattle.battle();
        long t2 = System.currentTimeMillis();
        long r1 = t2 - t1;
        logger.info("cricketBattle.battle() cost: {}", r1);
        CricketProto.CricketBattleLogPush.Builder cricketBattleLogPushBuilder = CricketProto.CricketBattleLogPush.newBuilder();
        cricketBattleLogPushBuilder.setBattleLog(battleLog);
    }

    public static void receiveDefendBattleLog(CricketProto.CricketDefendBattleLogReqMsg reqMsg) {
        CricketWaitHandleBattleLog cricketWaitHandleBattleLog = CricketWaitHandleBattleLog.getInstance();
        cricketWaitHandleBattleLog.setOriginServerId(reqMsg.getOriginServerId());
        cricketWaitHandleBattleLog.setOriginId(reqMsg.getOriginId());
        cricketWaitHandleBattleLog.setUserId(reqMsg.getUserId());
        cricketWaitHandleBattleLog.setBattleLog(reqMsg);
        handleDefendBattleLog(cricketWaitHandleBattleLog.getBattleLog(), false);
    }


    public static boolean handleDefendBattleLog(CricketProto.CricketDefendBattleLogReqMsg cricketDefendBattleLogReqMsg, boolean isSameServerId) {
        long userId = cricketDefendBattleLogReqMsg.getUserId();
        long addRankScore = cricketDefendBattleLogReqMsg.getAddRankScore();

        CricketProto.CricketBattleLog.Builder battleLogBuilder = cricketDefendBattleLogReqMsg.getBattleLog().toBuilder();

        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        long afterRankScore = 0;
        if (onlinePlayer != null) {
            CricketModule cricketModule = onlinePlayer.getModule(CricketModule.class);
            UserCricketData userCricketData = cricketModule.getUserCricketData();
            if (userCricketData == null) {
                return false;
            }
            // 重置下轮次
            cricketModule.changeCourtRound(cricketDefendBattleLogReqMsg.getRound());
            refreshUserCricketData(userCricketData);
            if (userCricketData.getDefendFailScore() + Math.abs(addRankScore) >= GameConfig.CRICKET_FIGHT_DEDUCTION_MAX) {
                // 最大可扣除分数
                addRankScore = -Math.max(0, GameConfig.CRICKET_FIGHT_DEDUCTION_MAX - userCricketData.getDefendFailScore());
                battleLogBuilder.setAddRankScore(1, (int) addRankScore);
            }
            userCricketData.setRankScore(userCricketData.getRankScore() + addRankScore);
            afterRankScore = userCricketData.getRankScore();
            if (addRankScore < 0) {
                userCricketData.setDefendFailScore(userCricketData.getDefendFailScore() + (-addRankScore));
                userCricketData.setLastDefendFailScoreTime(System.currentTimeMillis());
            }
        } else {
            UserCricketData userCricketData = UserCricketBussiness.getUserCricketData(userId);
            if (userCricketData == null) {
                return false;
            }
            if (userCricketData.getCourtRound() != cricketDefendBattleLogReqMsg.getRound() && cricketDefendBattleLogReqMsg.getRound() != 0) {
                // 需要重置离线用户的一些数据
                CricketMatchData cricketMatchData = userCricketData.getCricketMatchData();
                if (cricketMatchData != null) {
                    cricketMatchData.setTargetDefenseData(null);
                    cricketMatchData.setPreReduceProperty(null);
                }
                // 回到初始分
                userCricketData.setCourtRound(cricketDefendBattleLogReqMsg.getRound());
                userCricketData.setRankScore(GameConfig.CRICKET_FIGHT_BEGIN_RANK_SCORE);
                userCricketData.setShowCourtRank(false);
                userCricketData.setUpdateOption();

                Map<Integer, CricketData> cricketDataMap = UserCricketBussiness.getCricketDataMap(userId);
                // 刷新蛐蛐数据
                for (CricketData cricketData : cricketDataMap.values()) {
                    cricketData.setMatchTimes(0);
                    cricketData.setLastMatchTime(System.currentTimeMillis());
                    // 保存数据
                    UserCricketBussiness.updateCricket(cricketData);
                }
            }
            refreshUserCricketData(userCricketData);
            if (userCricketData.getDefendFailScore() + Math.abs(addRankScore) >= GameConfig.CRICKET_FIGHT_DEDUCTION_MAX) {
                // 最大可扣除分数
                addRankScore = -Math.max(0, GameConfig.CRICKET_FIGHT_DEDUCTION_MAX - userCricketData.getDefendFailScore());
                battleLogBuilder.setAddRankScore(1, (int) addRankScore);
            }
            userCricketData.setRankScore(userCricketData.getRankScore() + addRankScore);
            if (addRankScore < 0) {
                userCricketData.setDefendFailScore(userCricketData.getDefendFailScore() + (-addRankScore));
                userCricketData.setLastDefendFailScoreTime(System.currentTimeMillis());
            }
            UserCricketBussiness.updateUserCricket(userCricketData);
            afterRankScore = userCricketData.getRankScore();
        }
        // 同步积分到跨服
        //积分变化都要上传
        CricketProto.CricketDefenseRankScoreUpdateReqMsg.Builder defenseRankScoreUpdateReqBuilder = CricketProto.CricketDefenseRankScoreUpdateReqMsg.newBuilder();
        defenseRankScoreUpdateReqBuilder.setUserId(userId);
        defenseRankScoreUpdateReqBuilder.setRankScore(afterRankScore);
        GamePlayerMgr.sendPacket(userId, YanQuMessageUtils.buildMessage(CrossProtocol.C_CRICKET_DEFENSE_RANK_SCORE_UPDATE, defenseRankScoreUpdateReqBuilder));

        addBattleLog(userId, battleLogBuilder.build(), 1);
        if (!isSameServerId) {
            CricketProto.CricketDefendBattleLogSuccessReqMsg.Builder builder = CricketProto.CricketDefendBattleLogSuccessReqMsg.newBuilder();
            builder.setOriginServerId(cricketDefendBattleLogReqMsg.getOriginServerId());
            builder.setOriginId(cricketDefendBattleLogReqMsg.getOriginId());
            GamePlayerMgr.sendToGameServer(builder.getOriginServerId(), GameProtocol.S_CRICKET_DEFENDER_HANDLE_SUCCESS, cricketDefendBattleLogReqMsg.getFromUserId(), builder, null);
        }
        if (onlinePlayer != null) {
            CricketProto.CricketRedDotRespMsg.Builder builder = CricketProto.CricketRedDotRespMsg.newBuilder();
            builder.setBattleLog(true);
            onlinePlayer.sendPacket(ClientProtocol.U_CRICKET_RED_DOT, builder);
        }
        return true;
    }

    /**
     * 刷新用户的数据
     */
    public static void refreshUserCricketData(UserCricketData userCricketData) {
        long lastDefendFailScoreTime = userCricketData.getLastDefendFailScoreTime();
        long currentTimeMillis1 = System.currentTimeMillis();
        if (!DateHelper.isSameDay(lastDefendFailScoreTime / 1000, currentTimeMillis1 / 1000)) {
            userCricketData.setDefendFailScore(0);
            userCricketData.setLastDefendFailScoreTime(currentTimeMillis1);
        }
    }

    /**
     * 加入战报列表
     *
     * @param userId
     * @param battleLog
     */
    public static long addBattleLog(long userId, CricketProto.CricketBattleLog battleLog, int battleType) {
        DbUserCricketBattleLog dbUserCricketBattleLog = DbUserCricketBattleLog.getInstance();
        dbUserCricketBattleLog.setUserId(userId);
        dbUserCricketBattleLog.setBattleType(battleType);
        String score = battleLog.getMatchRound().getScore();
        if (battleLog.getAddRankScoreList().size() == 2) {
            score = String.format("%s;%d:%d", score, battleLog.getAddRankScore(0), battleLog.getAddRankScore(1));
        }
        dbUserCricketBattleLog.setScore(score);
        dbUserCricketBattleLog.setBattleTimestamp(battleLog.getTimestamp());
        for (CricketProto.CricketUserBattleDataTemp cricketUserBattleDataTemp : battleLog.getMatchRound().getUserBattleDataList()) {
            CricketUserBaseInfo userBaseInfo = CricketUserBaseInfo.getInstance(cricketUserBattleDataTemp);
            dbUserCricketBattleLog.getUserBaseInfoList().add(userBaseInfo);
        }
        dbUserCricketBattleLog.setNeedInsert(true);
        dbUserCricketBattleLog.refreshUpdateTime();

        dbUserCricketBattleLog = CricketGameBusiness.saveDbUserCricketBattleLog(dbUserCricketBattleLog);
        DbUserCricketBattleLogDetail dbUserCricketBattleLogDetail = DbUserCricketBattleLogDetail.getInstance();
        dbUserCricketBattleLogDetail.setBattleLogId(dbUserCricketBattleLog.getId());
        dbUserCricketBattleLogDetail.setCricketBattleLog(battleLog);
        dbUserCricketBattleLogDetail.setNeedInsert(true);
        dbUserCricketBattleLogDetail.refreshUpdateTime();
        CricketGameBusiness.saveDbUserCricketBattleLogDetail(dbUserCricketBattleLogDetail);

        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (onlinePlayer != null) {
            CricketModule cricketModule = onlinePlayer.getModule(CricketModule.class);
            cricketModule.addDbCricketBattleLog(dbUserCricketBattleLog);
        }
        return dbUserCricketBattleLog.getId();
    }


    public static void sendSyncDbBattleLog() {
        for (DbUserCricketWaitSendBattleLog dbUserCricketWaitSendBattleLog : waitSendSyncCricketDbBattleLog.values()) {
            GamePlayerMgr.sendToGameServer(dbUserCricketWaitSendBattleLog.getToServerId(), GameProtocol.S_CRICKET_DEFENDER_HANDLE_BATTLE_LOG, dbUserCricketWaitSendBattleLog.getBattleLog().getUserId(), dbUserCricketWaitSendBattleLog.getBattleLog().toBuilder(), null);
        }
    }

    public static void receiveDefendHandleSuccess(CricketProto.CricketDefendBattleLogSuccessReqMsg reqMsg) {
        long serverId = GameServer.getInstance().getServerId();
        if (serverId != reqMsg.getOriginServerId()) {
            return;
        }

        DbUserCricketWaitSendBattleLog dbUserCricketWaitSendBattleLog = waitSendSyncCricketDbBattleLog.get(reqMsg.getOriginId());
        if(null == dbUserCricketWaitSendBattleLog){
            return;
        }
        //这个时候，如果数据库里还没有这条数据，就清掉了，不用写入
        if (dbUserCricketWaitSendBattleLog.isNeedInsert()) {
            waitSendSyncCricketDbBattleLog.remove(dbUserCricketWaitSendBattleLog.getOriginId());
        } else {
            dbUserCricketWaitSendBattleLog.setSync(1);
            dbUserCricketWaitSendBattleLog.refreshUpdateTime();
        }

    }


    public static ConcurrentHashMap<Long, DbUserCricketWaitSendBattleLog> getWaitSendSyncCricketDbBattleLog() {
        return waitSendSyncCricketDbBattleLog;
    }

    public static CricketBattleData toCricketBattleData(CricketProto.CricketTempMsg cricketTemp) {
        CricketProto.CricketMatchDataTemp.Builder cricketMatchDataTemp = CricketPb.parseCricketMatchDataTemp(cricketTemp);
        cricketMatchDataTemp.addAllAttackSkill(cricketTemp.getAttackSkillList());
        cricketMatchDataTemp.addAllInitSkill(cricketTemp.getInitSkillList());
        cricketMatchDataTemp.addAllSkill(cricketTemp.getSkillList());
        cricketMatchDataTemp.addAllBattleSkill(cricketTemp.getAttackSkillList());
        cricketMatchDataTemp.addAllBattleSkill(cricketTemp.getInitSkillList());
        cricketMatchDataTemp.addAllBattleSkill(cricketTemp.getSkillList());
        CricketProto.CricketTalentTempMsg.Builder talentBuilder = CricketProto.CricketTalentTempMsg.newBuilder();
        talentBuilder.setAtk(0);
        talentBuilder.setHp(0);
        talentBuilder.setPower(0);
        cricketMatchDataTemp.setTalent(talentBuilder);
        CricketBattleData cricketBattleData = CricketBattleData.getInstance(cricketMatchDataTemp.build());
        return cricketBattleData;
    }


    public static void bindCricketToPatrons(int activityId, long userId, int patronsId) {
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        if (player != null) {
            CricketModule cricketModule = player.getModule(CricketModule.class);
            CricketData cricketData = getUserCricketByPatrons(patronsId,cricketModule.getCricketDataMap());
            if (cricketData != null) {
                cricketModule.addPatronsBindData(activityId,patronsId,cricketData.getCricketId());
            }
        }else {
            Map<Integer, CricketData> vehicleMap = UserCricketBussiness.getCricketDataMap(userId);
            int cricketId = 0;
            for (CricketData data : vehicleMap.values()) {
                if (data.getEquipPatronsId() == patronsId) {
                    cricketId = data.getCricketId();
                }
            }
            if (cricketId != 0) {
                Map<Integer, PatronsCricketBindingData> dataMap = UserCricketBussiness.getCricketBindDataMap(userId);
                PatronsCricketBindingData data = dataMap.get(cricketId);
                if (data == null) {
                    data = new PatronsCricketBindingData();
                    data.setCricketId(cricketId);
                    data.setUserId(userId);
                    data.setInsertOption();
                }
                if (data.getActivityIdList().contains(activityId) && data.getPatronsId() == patronsId) {
                    return;
                }
                data.setPatronsId(patronsId);
                data.addActivityId(activityId);
                data.setLastUpdateTime(System.currentTimeMillis());
                if (data.isInsertOption()) {
                    UserCricketBussiness.addCricketBind(data);
                }else{
                    UserCricketBussiness.updateCricketBind(data);
                }
            }
        }
    }

    public static List<List<Integer>> getCricketFightOpenTimeList() {
        List<List<Integer>> cricketFightOpenTimeList = new ArrayList<>();
        String[] split1 = GameConfig.CRICKET_FIGHT_OPEN_TIME.split("\\|");
        for (String s : split1) {
            String[] split2 = s.split(";");
            if (split2.length != 2) {
                continue;
            }
            List<Integer> list = new ArrayList<>();
            list.add(Integer.parseInt(split2[0]));
            list.add(Integer.parseInt(split2[1]));
            cricketFightOpenTimeList.add(list);
        }
        return cricketFightOpenTimeList;
    }

    public static Property getCricketFightOutCost(int times) {
        // 付费次数
        times = Math.max(0, times - GameConfig.CRICKET_FIGHT_OUT_FREE_MAX);
        List<Property> cricketFightOutCostList = new ArrayList<>();
        String cricketFightOutCost = GameConfig.CRICKET_FIGHT_OUT_COST;
        String[] split = cricketFightOutCost.split("\\|");
        for (String s : split) {
            Property property = PropertyHelper.parseStringToProperty(s);
            cricketFightOutCostList.add(property);
        }
        if (times > cricketFightOutCostList.size() - 1) {
            times = cricketFightOutCostList.size() - 1;
        }
        if (times < 0) {
            times = 0;
        }
        return cricketFightOutCostList.get(times);
    }

    public static List<Integer> getCricketFightReportHotValueLimitList() {
        return StringUtils.stringToIntegerList(GameConfig.CRICKET_FIGHT_REPORT_HOT_VALUE_LIMIT, "\\|");
    }

    public static void reloadActivityData() {
        getLogger().info("reload cricket begin");
        // 拿活动
        List<ActivityInfo> list = NormalActivityMgr.getOpenActivityInfoList(eActivityType.CricketMallActivity.getValue());
        if (list.isEmpty()) {
            config.setActivityInfo(null);
            getLogger().info("reload cricket finish, no activity in show time.");
            return;
        }
        ActivityInfo activityInfo = list.get(0);
        config.setActivityInfo(activityInfo);
        Map<String, ActivityConfig> configMap = NormalActivityMgr.getActivityConfigMap(activityInfo.getActivityId());
        if (configMap != null && configMap.containsKey("CRICKET_MALL_TOKEN_SET_TIME")) {
            config.setTokenResetTime(configMap.get("CRICKET_MALL_TOKEN_SET_TIME").getIntValue());
        }
        // 在线玩家刷一下战令
        for (GamePlayer gamePlayer : GamePlayerMgr.getAllOnlinePlayer()) {
            CricketModule cricketModule = gamePlayer.getModule(CricketModule.class);
            cricketModule.checkToken();
            cricketModule.syncConfig();
        }
    }

    public static int getCricketFightScoreAttack(int winNum) {
        if (winNum > GameConfig.CRICKET_FIGHT_DEF_TEAM_NUM) {
            return 0;
        }
        return config.getCricketFightScoreAttack().get(GameConfig.CRICKET_FIGHT_DEF_TEAM_NUM - winNum);
    }

    public static int getCricketFightScoreDefend(int winNum) {
        if (winNum > GameConfig.CRICKET_FIGHT_DEF_TEAM_NUM) {
            return 0;
        }
        return config.getCricketFightScoreDefend().get(GameConfig.CRICKET_FIGHT_DEF_TEAM_NUM - winNum);
    }


    /**
     * 获取升阶配置
     *
     * @param cricketId 蛐蛐id
     * @param title     军衔
     */
    public static CricketUpConfig getCricketUpConfig(int cricketId, int title, int littleTitle) {
        int quality = getCricketQuality(cricketId);
        for (CricketUpConfig config : config.getCricketUpConfigMap().values()) {
            if (quality == config.getCricketQuality() && title == config.getTitle() && littleTitle == config.getLittleTitle()) {
                return config;
            }
        }
        return null;
    }

    /**
     * 获取蛐蛐品质
     * 神兽的品质为5，但实际计算要以6来算
     * @param cricketId
     * @return
     */
    public static int getCricketQuality(int cricketId) {
        CricketConfig cricketConfig = config.getCricketConfig(cricketId);
        if (cricketConfig == null) {
            return 0;
        }
        int quality = cricketConfig.getQuality();
        // 特殊处理无双蛐蛐获取时品质读6的配置
        List<Integer> wsCricketIdList = StringUtils.stringToIntegerList(GameConfig.CRICKET_CHANGE_GET, "\\|");
        if (wsCricketIdList.contains(cricketId)) {
            quality = 6;
        }
        return quality;
    }


    /**
     * 获取下一阶的升阶配置
     */
    public static CricketUpConfig getNextCricketUpConfig(int cricketId, int title, int littleTitle) {
        // 先获取下一品阶
        CricketUpConfig cricketUpConfig = getCricketUpConfig(cricketId, title, littleTitle + 1);
        if (cricketUpConfig != null) {
            return cricketUpConfig;
        }
        // 品阶已满获取下一军衔
        return getCricketUpConfig(cricketId, title + 1, 1);
    }

    /**
     * 获取特殊事件的蛐蛐列表
     */
    public static List<Integer> getEventCricketList() {
        List<Integer> list = new ArrayList<>();
        // 蛐蛐数量#权重|蛐蛐数量#权重……（蛐蛐数量按绿蓝紫橙红配置，先确定用哪一套数量，再随机具体蛐蛐）
        String[] eventPools = GameConfig.CRICKET_CATCH_EVENT_POOL.split("\\|");
        // 总权重
        int sumWeight = 0;
        for (String eventPool : eventPools) {
            sumWeight += Integer.parseInt(eventPool.split("#")[1]);
        }
        // 随机一个权重
        int randomWeight = randomHelper.next(0, sumWeight);
        // 当前权重
        int curWeight = 0;
        String pool = "";
        for (String eventPool : eventPools) {
            String[] split = eventPool.split("#");
            curWeight += Integer.parseInt(split[1]);
            if (randomWeight < curWeight) {
                pool = split[0];
                break;
            }
        }
        // 获取绿蓝紫橙红数量
        String[] nums = pool.split(";");
        for (int i = 0; i < nums.length; i++) {
            // 品质
            int quality = i + 1;
            // 数量
            int num = Integer.parseInt(nums[i]);
            for (int t = 0; t < num; t++) {
                CricketConfig cricketConfig = randomGetCricketByQuality(quality);
                if (cricketConfig != null) {
                    list.add(cricketConfig.getId());
                }
            }
        }
        return list;
    }

    /**
     * 根据品质随机获取一只蛐蛐
     */
    public static CricketConfig randomGetCricketByQuality(int quality) {
        Map<Integer, CricketConfig> cricketConfigMap = config.getCricketConfigMap();
        if (cricketConfigMap == null || cricketConfigMap.size() == 0) {
            return null;
        }
        List<CricketConfig> list = new ArrayList<>();
        // 排除圣兽
//        List<Integer> shengshouList = StringUtils.stringToIntegerList(GameConfig.CRICKET_CHANGE_GET, "\\|");
        for (CricketConfig cricketConfig : cricketConfigMap.values()) {
            if (cricketConfig.getGetByEvent() == 0) {
                continue;
            }
            if (quality == cricketConfig.getQuality()) {
                list.add(cricketConfig);
            }
        }
        return list.get(randomHelper.next(0, list.size()));
    }

    /**
     * 随机品质
     *
     * @param scenceId 场景id
     */
    public static int getCatchQualityByWeight(int scenceId) {
        int quality = 0;
        CricketScenceConfig scenceConfig = config.getCricketScenceConfig(scenceId);
        if (scenceConfig == null) {
            return quality;
        }
        // 获取权重
        String catchWeight = scenceConfig.getCatchWeight();
        String[] catchWeightSplit = catchWeight.split("\\|");
        // 总权重
        int sumWeight = 0;
        for (String weight : catchWeightSplit) {
            sumWeight += Integer.parseInt(weight);
        }
        // 随机一个权重
        int randomWeight = randomHelper.next(0, sumWeight);
        // 当前权重
        int curWeight = 0;
        // 抽品质
        int targetQuality = 1;
        for (int idx = 0; idx < catchWeightSplit.length; idx++) {
            curWeight += Integer.parseInt(catchWeightSplit[idx]);
            if (randomWeight < curWeight) {
                targetQuality = idx + 1;
                break;
            }
        }
        return targetQuality;
    }


    /**
     * 筛选出满足的蛐蛐库
     *
     * @param scenceId 场景id
     * @param quality  品质
     */
    public static List<String> matchLibraryWithQuality(int scenceId, int quality) {
        List<String> matchLibrary = new ArrayList<>();
        CricketScenceConfig scenceConfig = config.getCricketScenceConfig(scenceId);
        if (scenceConfig == null) {
            return matchLibrary;
        }
        // 蛐蛐库
        String cricketLibrary = scenceConfig.getCricketLibrary();
        String[] cricketLibrarySplit = cricketLibrary.split("\\|");
        for (String item : cricketLibrarySplit) {
            String[] itemSplit = item.split(";");
            int cricketId = Integer.parseInt(itemSplit[0]);
            // 筛选对应品质的
            CricketConfig cricketConfig = config.getCricketConfig(cricketId);
            if (cricketConfig == null || cricketConfig.getQuality() != quality) {
                continue;
            }
            matchLibrary.add(item);
        }
        return matchLibrary;
    }


    /**
     * 从蛐蛐库中根据权重抽取蛐蛐
     */
    public static int drawCricketWithLibrary(List<String> library) {
        // 总权重
        int sumWeight = 0;
        for (String item : library) {
            String[] itemSplit = item.split(";");
            int weight = Integer.parseInt(itemSplit[1]);
            sumWeight += weight;
        }
        // 随机一个权重
        int randomWeight = randomHelper.next(0, sumWeight);
        // 当前权重
        int curWeight = 0;
        for (String item : library) {
            String[] itemSplit = item.split(";");
            int cricketId = Integer.parseInt(itemSplit[0]);
            curWeight += Integer.parseInt(itemSplit[1]);
            if (randomWeight < curWeight) {
                return cricketId;
            }
        }
        return 0;
    }

    /**
     * 获取第一张场景的id
     */
    public static int getFirstScenceId() {
        for (CricketScenceConfig config : config.getCricketScenceConfigMap().values()) {
            if (config.getOrder() == 1) {
                return config.getId();
            }
        }
        return 0;
    }

    /**
     * 获取下一个场景的id
     *
     * @param scenceId 场景id
     */
    public static int getNextScenceId(int scenceId) {
        CricketScenceConfig cricketScenceConfig = config.getCricketScenceConfigMap().get(scenceId);
        if (cricketScenceConfig == null) {
            return 0;
        }
        // 当前场景的顺序
        int curOrder = cricketScenceConfig.getOrder();
        int nextOrder = curOrder + 1;
        if (curOrder >= config.getMaxOrder()) {
            // 从头切换
            nextOrder = 1;
        }
        for (CricketScenceConfig scenceConfig : config.getCricketScenceConfigMap().values()) {
            if (scenceConfig.getOrder() == nextOrder) {
                return scenceConfig.getId();
            }
        }
        return 0;
    }

    public List<List<Integer>> CRICKET_FIGHT_FORCE_PRO() {
        String s = "0;300;500|200;200;600|500;100;700|1000;50;800";
        String[] strings = s.split("\\|");
        List<List<Integer>> list = new ArrayList<>();
        for (String string : strings) {
            List<Integer> integers = StringUtils.stringToIntegerList(string, ";");
            list.add(integers);
        }
        return list;
    }



    private int randPrewarInspireSkillStar() {
        String weightStr = GameConfig.CRICKET_INSPIRE_SKILL_GET_WEIGHT;

        List<String> weightList = StringUtils.stringToStringList(weightStr, "\\|");
        Map<Integer, Integer> starWeight = new LinkedHashMap<>();
        // 总权重
        int sumWeight = 0;
        int star = 0;
        for (String s : weightList) {
            star++;
            int weight = Integer.parseInt(s);
            starWeight.put(star, weight);
            sumWeight += weight;
        }
        // 随机一个权重
        int randomWeight = randomHelper.next(0, sumWeight);
        // 当前权重
        int curWeight = 0;
        for (Map.Entry<Integer, Integer> entry : starWeight.entrySet()) {
            curWeight = curWeight + entry.getValue();
            if (randomWeight < curWeight) {
                return entry.getKey();
            }
        }
        return 1;
    }

    public PreWarInspireSkillInfo randPrewarInspireSkill() {
        PreWarInspireSkillInfo preWarInspireSkillInfo = new PreWarInspireSkillInfo();
        int star = randPrewarInspireSkillStar();
        String weightStr = "633131;10|633141;10|633151;10|633161;10";
        if (star == 1) {
            weightStr = GameConfig.CRICKET_INSPIRE_SKILL_STAR_GET_WEIGHT_1;
        } else if (star == 2) {
            weightStr = GameConfig.CRICKET_INSPIRE_SKILL_STAR_GET_WEIGHT_2;
        } else if (star == 3) {
            weightStr = GameConfig.CRICKET_INSPIRE_SKILL_STAR_GET_WEIGHT_3;
        } else if (star == 4) {
            weightStr = GameConfig.CRICKET_INSPIRE_SKILL_STAR_GET_WEIGHT_4;
        } else if (star == 5) {
            weightStr = GameConfig.CRICKET_INSPIRE_SKILL_STAR_GET_WEIGHT_5;
        }
        List<String> weightList = StringUtils.stringToStringList(weightStr, "\\|");
        Map<Integer, Integer> weightMap = new LinkedHashMap<>();
        // 总权重
        int sumWeight = 0;
        for (String s : weightList) {
            String[] split = s.split(";");
            int skillId = Integer.parseInt(split[0]);
            int weight = Integer.parseInt(split[1]);
            weightMap.put(skillId, weight);
            sumWeight += weight;
            preWarInspireSkillInfo.getSkillPool().add(skillId);
        }
        // 随机一个权重
        int randomWeight = randomHelper.next(0, sumWeight);
        // 当前权重
        int curWeight = 0;
        for (Map.Entry<Integer, Integer> entry : weightMap.entrySet()) {
            curWeight = curWeight + entry.getValue();
            if (randomWeight < curWeight) {
                preWarInspireSkillInfo.setRandSkillId(entry.getKey());
                return preWarInspireSkillInfo;
            }
        }
        preWarInspireSkillInfo.setRandSkillId(63313);
        return preWarInspireSkillInfo;

    }

    /**
     * 蛐蛐满阶后，再次获得转换蛐蛐秘籍的数量
     *
     * @param cricketId 蛐蛐id
     */
    public static String getCricketCatchMaxTurn(int cricketId) {
        int quality = getCricketQuality(cricketId);
        int qualityIdx = Math.max(0, quality - 1);
        List<String> turnList = StringUtils.stringToStringList(GameConfig.CRICKET_CATCH_MAX_TURN, "\\|");
        return turnList.get(Math.min(qualityIdx, turnList.size() - 1));
    }





    public static CricketConfig getCricketConfigByPartonSkill(int skillId) {
        return config.getCricketConfigMap().values()
                .stream()
                .filter(config -> skillId == config.getPartonSkill())
                .findFirst()
                .orElse(null);
    }

    /**
     * 获取虫师技能参数
     *
     * @param start                  技能星级
     * @param cricketSkillBreakCount 蛐蛐技能突破次数
     */
    public static String getPartonSkillParam(int start, int cricketSkillBreakCount) {
        String param = "";
        if (start == 1) {
            param = GameConfig.CRICKET_PARTON_SKILL_PARAM_1;
        } else if (start == 2) {
            param = GameConfig.CRICKET_PARTON_SKILL_PARAM_2;
        } else if (start == 3) {
            param = GameConfig.CRICKET_PARTON_SKILL_PARAM_3;
        } else if (start == 4) {
            param = GameConfig.CRICKET_PARTON_SKILL_PARAM_4;
        } else if (start == 5) {
            param = GameConfig.CRICKET_PARTON_SKILL_PARAM_5;
        } else if (start == 6) {
            param = GameConfig.CRICKET_PARTON_SKILL_PARAM_6;
        }
        List<String> list = StringUtils.stringToStringList(param, "\\|");
        if (list.size() == 0) {
            return "";
        }
        return list.get(Math.max(0, Math.min(cricketSkillBreakCount, list.size() - 1)));
    }




    /**
     * 获取膜拜奖励
     */
    public static String getWorshipReward() {
        return GameConfig.CRICKET_SEASON_END_WORSHIP_REWARD;
    }


    public static int getCricketFightScareNumMax() {
        return 3;
    }

    /**
     * 被动技能是否唯一生效
     */
    public static boolean isSingleEffectSkill(int skillId) {
        List<String> skillList = StringUtils.stringToStringList(GameConfig.CRICKET_SKILLS_GET_WEIGHT, "\\|");
//        for (String skill : skillList) {
//            List<Integer> params = StringUtils.stringToIntegerList(skill, ";");
//            if (skillId == params.get(0)) {
//                return params.get(2) == 1;
//            }
//        }
        return false;
    }


    public static int battleLogLimit() {
        List<Integer> list = StringUtils.stringToIntegerList(GameConfig.CRICKET_FIGHT_REPORT_HOT_VALUE_LIMIT, "\\|");
        return list.get(2);
    }

    /**
     * 获取资质
     */
    public static CricketTalent calcCricketTalent(CricketData cricketData) {
        CricketTalent cricketTalent = new CricketTalent();
        if (cricketData == null) {
            return cricketTalent;
        }
        CricketConfig config = CricketMgr.getConfig().getCricketConfig(cricketData.getCricketId());
        if (config == null) {
            return cricketTalent;
        }
        // 血攻气资质
        List<Integer> configTalentList = StringUtils.stringToIntegerList(config.getTalent(), "\\|");
        List<Integer> maxTalentList = StringUtils.stringToIntegerList(GameConfig.CRICKET_MAX_TALENT, "\\|");
        // 血
        cricketTalent.setHp(Math.min(maxTalentList.get(0), configTalentList.get(0)));
        // 攻
        cricketTalent.setAtk(Math.min(maxTalentList.get(1), configTalentList.get(1)));
        // 气
        cricketTalent.setPower(Math.min(maxTalentList.get(2), configTalentList.get(2)));
        cricketData.setCricketTalent(cricketTalent);
        return cricketTalent;
    }

    /**
     * 计算属性
     *
     * @param cricketData 蛐蛐数据
     */
    public static void calcProperty(CricketData cricketData) {
        // 属性计算公式
        long l = 0;
        CricketUpConfig cricketUpConfig = CricketMgr.getCricketUpConfig(cricketData.getCricketId(), cricketData.getTitle(), cricketData.getLittleTitle());
        if (cricketUpConfig != null) {
            l = Long.parseLong(cricketUpConfig.getAddProperty());
        } else {
            l = 1000;
        }
        // 资质
        CricketTalent cricketTalent = calcCricketTalent(cricketData);
        // 血量资质千分数
        long f1 = cricketTalent.getHp();
        // 攻击资质千分数
        long f2 = cricketTalent.getAtk();
        // 气势资质千分数
        long f3 = cricketTalent.getPower();
        // 属性
        CricketProperty cricketProperty = new CricketProperty();
        // 属性资质关联参数
        List<Integer> params = StringUtils.stringToIntegerList(GameConfig.CRICKET_ATTRIBUTE_TALENT_PARAM, "\\|");
        int m1 = params.get(0);
        int m2 = params.get(1);
        int m3 = params.get(2);
        int m4 = params.get(3);
        int m5 = params.get(4);
        int m6 = params.get(5);

        // 血量属性
        long hp = BigDecimal.valueOf(Math.pow(BigDecimal.valueOf(f1).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP).doubleValue(), BigDecimal.valueOf(m4).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP).doubleValue()))
                .multiply(BigDecimal.valueOf(m1).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP))
                .multiply(BigDecimal.valueOf(l).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP))
                .setScale(0, BigDecimal.ROUND_DOWN).longValue();
        cricketProperty.setHp(hp);

        // 攻击属性
        long atk = BigDecimal.valueOf(Math.pow(BigDecimal.valueOf(f2).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP).doubleValue(), BigDecimal.valueOf(m5).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP).doubleValue()))
                .multiply(BigDecimal.valueOf(m2).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP))
                .multiply(BigDecimal.valueOf(l).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP))
                .setScale(0, BigDecimal.ROUND_DOWN).longValue();
        cricketProperty.setAtk(atk);

        // 气势属性
        long power = BigDecimal.valueOf(f3).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP)
                .multiply(BigDecimal.valueOf(m3).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP))
                .multiply(BigDecimal.valueOf(Math.pow(BigDecimal.valueOf(l).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP).doubleValue(), BigDecimal.valueOf(m6).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP).doubleValue())))
                .setScale(0, BigDecimal.ROUND_DOWN).longValue();
        cricketProperty.setPower(power);

        // 战力
        // 技能总星级 n
        long n = 0;
        for (CricketSkill cricketSkill : cricketData.getAllCricketSkillList()) {
            if (cricketSkill == null) {
                continue;
            }
            SkillInfo skillInfo = SkillMgr.getSkillInfo(cricketSkill.getSkillId());
            if (skillInfo == null) {
                continue;
            }
            n += skillInfo.getStars();
        }
        List<Integer> powerParams = StringUtils.stringToIntegerList(GameConfig.CRICKET_POWER_PARAM, "\\|");
        int x1 = powerParams.get(0);
        int x2 = powerParams.get(1);
        int x3 = powerParams.get(2);
        // 蛐蛐的总战斗力
        long ability = BigDecimal.valueOf(Math.pow(BigDecimal.valueOf(f1).add(BigDecimal.valueOf(f2)).add(BigDecimal.valueOf(f3)).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP)
                        .multiply(BigDecimal.valueOf(l).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP)).doubleValue(), BigDecimal.valueOf(x3).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP).doubleValue()))
                .multiply(BigDecimal.ONE.add(BigDecimal.valueOf(n).multiply(BigDecimal.valueOf(x1)).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP)))
                .multiply(BigDecimal.valueOf(x2).divide(BigDecimal.valueOf(1000), 8, BigDecimal.ROUND_UP))
                .setScale(0, BigDecimal.ROUND_DOWN).longValue();
        cricketProperty.setAbility(ability);
        cricketData.setCricketProperty(cricketProperty);
        // 计算技能buff属性加成
        calcBuffAddProperty(cricketData);
    }

    /**
     * 获取生效的技能(过滤掉不生效、低星级不可叠加的技能)
     */
    public static List<CricketSkill> getAllEffectSkill(CricketData cricketData) {
        List<CricketSkill> effectSkillList = new ArrayList<>();
        List<CricketSkill> allCricketSkillList = cricketData.getAllCricketSkillListExcludeInit();
        Map<Integer, CricketSkill> map = new ConcurrentHashMap<>();
        for (CricketSkill cricketSkill : allCricketSkillList) {
            if (cricketSkill == null) {
                continue;
            }
            int skillId = cricketSkill.getSkillId();
            SkillInfo skillInfo = SkillMgr.getSkillInfo(skillId);
            if (skillInfo == null) {
                continue;
            }
            boolean singleEffectSkill = CricketMgr.isSingleEffectSkill(skillId);
            if (!singleEffectSkill) {
                effectSkillList.add(cricketSkill);
                continue;
            }
            int type = skillInfo.getType();
            // 唯一生效的先加到类型map里处理
            if (!map.containsKey(type)) {
                map.put(type, cricketSkill);
            } else {
                CricketSkill tempSkill = map.get(type);
                SkillInfo tempSkillInfo = SkillMgr.getSkillInfo(tempSkill.getSkillId());
                if (skillInfo.getStars() >= tempSkillInfo.getStars()) {
                    // 替换掉
                    map.put(type, cricketSkill);
                }
            }
        }
        // map剩下的都是生效的
        effectSkillList.addAll(map.values());
        effectSkillList.addAll(cricketData.getInitSkillList());
        return effectSkillList;
    }

    /**
     * 计算技能buff属性加成
     *
     * @param cricketData 蛐蛐数据
     */
    public static void calcBuffAddProperty(CricketData cricketData) {
        CricketProperty addProperty = new CricketProperty();
        // 血加成千分比
        int hpRate = 0;
        // 攻加成千分比
        int atkRate = 0;
        // 气势加成千分比
        int powerRate = 0;
        List<CricketSkill> allEffectSkill = getAllEffectSkill(cricketData);
        for (CricketSkill skill : allEffectSkill) {
            int skillId = skill.getSkillId();
            SkillInfo skillInfo = SkillMgr.getSkillInfo(skillId);
            if (skillInfo == null) {
                continue;
            }
            if (skillInfo.getType() == eSkillType.CricketBattleSkill138.getValue()) {
                hpRate += skillInfo.getParamList().get(0);
            } else if (skillInfo.getType() == eSkillType.CricketBattleSkill139.getValue()) {
                atkRate += skillInfo.getParamList().get(0);
            } else if (skillInfo.getType() == eSkillType.CricketBattleSkill140.getValue()) {
                powerRate += skillInfo.getParamList().get(0);
            }
        }
        long addHp = BigDecimal.valueOf(cricketData.getCricketProperty().getHp()).multiply(BigDecimal.valueOf(hpRate)).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_DOWN).longValue();
        addProperty.setHp(addHp);
        long addAtk = BigDecimal.valueOf(cricketData.getCricketProperty().getAtk()).multiply(BigDecimal.valueOf(atkRate)).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_DOWN).longValue();
        addProperty.setAtk(addAtk);
        long addPower = BigDecimal.valueOf(cricketData.getCricketProperty().getPower()).multiply(BigDecimal.valueOf(powerRate)).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_DOWN).longValue();
        addProperty.setPower(addPower);
        cricketData.setAddProperty(addProperty);
    }

    /**
     * 初始化蛐蛐
     *
     * @param cricketId 蛐蛐id
     * @param userId
     */
    public static CricketData initCricket(int cricketId, long userId) {
        CricketData cricketData = new CricketData();
        CricketConfig config = CricketMgr.getConfig().getCricketConfig(cricketId);
        cricketData.setUserId(userId);
        cricketData.setCricketId(cricketId);
        cricketData.setQuality(config.getQuality());
        String[] beginTitleSplit = config.getBeginTitle().split("\\|");
        cricketData.setTitle(Integer.parseInt(beginTitleSplit[0]));
        cricketData.setLittleTitle(Integer.parseInt(beginTitleSplit[1]));
        cricketData.setBattleTimes(0);

        // 血攻气资质
        List<Integer> configTalentList = StringUtils.stringToIntegerList(config.getTalent(), "\\|");
        List<Integer> maxTalentList = StringUtils.stringToIntegerList(GameConfig.CRICKET_MAX_TALENT, "\\|");
        CricketTalent cricketTalent = new CricketTalent();
        // 血
        cricketTalent.setHp(Math.min(maxTalentList.get(0), configTalentList.get(0)));
        // 攻
        cricketTalent.setAtk(Math.min(maxTalentList.get(1), configTalentList.get(1)));
        // 气
        cricketTalent.setPower(Math.min(maxTalentList.get(2), configTalentList.get(2)));
        cricketData.setCricketTalent(cricketTalent);
        // 初始化时激活蛐蛐技能
        initSkill(cricketData);

        cricketData.setInsertOption();
        return cricketData;
    }

    /**
     * 初始攻击方式和天赋
     *
     * @param cricketData 蛐蛐数据
     */
    private static void initSkill(CricketData cricketData) {
        if (cricketData == null) {
            return;
        }
        int cricketId = cricketData.getCricketId();
        CricketSystemConfig config = CricketMgr.getConfig();
        CricketConfig cricketConfig = config.getCricketConfig(cricketId);
        if (cricketConfig == null) {
            return;
        }
        // 攻击列表
        List<CricketSkill> attackSkillList = new ArrayList<>();
        List<Integer> attackConfigSkillList = cricketConfig.getAttackSkillList();
        for (int skillId : attackConfigSkillList) {
            SkillInfo skillInfo = SkillMgr.getSkillInfo(skillId);
            if (skillInfo == null) {
                // 判断下技能是否存在
                continue;
            }
            if (attackSkillList.stream().anyMatch(cricketSkill -> skillId == cricketSkill.getSkillId())) {
                // 已添加
                continue;
            }
            attackSkillList.add(new CricketSkill(skillId));
        }
        cricketData.setAttackSkillList(attackSkillList);
        // 初始天赋
        List<CricketSkill> initSkillList = new ArrayList<>();
        List<Integer> initConfigSkillList = cricketConfig.getInitSkillList();
        for (int skillId : initConfigSkillList) {
            SkillInfo skillInfo = SkillMgr.getSkillInfo(skillId);
            if (skillInfo == null) {
                // 判断下技能是否存在
                continue;
            }
            if (initSkillList.stream().anyMatch(cricketSkill -> skillId == cricketSkill.getSkillId())) {
                // 已添加
                continue;
            }
            initSkillList.add(new CricketSkill(skillId));
        }
        cricketData.setInitSkillList(initSkillList);

        List<CricketEquipSkill> eSkillList = cricketData.getEquipSkillList();
        List<Integer> eSkillConfigList = cricketConfig.getEquipSkillList();
        for (int skillId : eSkillConfigList) {
            SkillInfo skillInfo = SkillMgr.getSkillInfo(skillId);
            if (skillInfo == null) {
                // 判断下技能是否存在
                continue;
            }
            if (eSkillList.stream().anyMatch(a -> skillId == a.getSkillId())) {
                // 已添加
                continue;
            }
            CricketEquipSkill newSkill = new CricketEquipSkill();
            newSkill.setUserId(cricketData.getUserId());
            newSkill.setCricketId(cricketId);
            newSkill.setSkillId(skillId);
            newSkill.setLv(1);
            newSkill.setInsertOption();
            eSkillList.add(newSkill);
        }

        cricketData.setEquipSkillList(eSkillList);
    }
}